package com.hepinghospital.user.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.util.UploadImageUtil;
import com.hjq.shape.view.ShapeTextView;
import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.eventbus.RefreshEvent;
import com.hepinghospital.user.ui.activity.eyecheck.BigImageActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyAskActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyFamilyActivity;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.DateTimeDialogFragment;
import com.hepinghospital.user.ui.dialog.PayDialog;
import com.hepinghospital.user.ui.dialog.PayTipDialog;
import com.hepinghospital.user.ui.dialog.RulesDialogFragment;
import com.hepinghospital.user.ui.dialog.SchudeleDialogFragment;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.hepinghospital.user.wxapi.WXPayEntryActivity;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.BaseJsonResponse;
import com.rest.response.CloudResponse;
import com.rest.response.Doctor;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.OrderResponse;
import com.rest.response.PayResponse;
import com.rest.response.Photo;
import com.rest.response.PicUploadResponse;
import com.rest.response.RegistrationDetailResponse;
import com.rest.response.StringResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import jz.joyoung.robot.util.UtilList;
import jz.joyoung.robot.util.UtilString;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * @Description: 图文问诊
 * @Author: lzp
 * @CreateDate: 2023/3/29 11:16
 * @UpdateRemark: 更新说明
 */
public class PayActivity extends BaseActivity {
    public static final int REQUEST_OPEN_CAMERA = 0x011;
    public static final int REQUEST_GALLERY = 0x022;

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edt_state)
    EditText edtState;
    @BindView(R.id.edt_past)
    EditText edtPast;
    @BindView(R.id.edt_allergy)
    EditText edtAllergy;
    @BindView(R.id.patient_name_container)
    RelativeLayout patient_name_container;
    @BindView(R.id.tv_hospital)
    TextView tv_hospital;
    @BindView(R.id.tv_star)
    TextView tv_star;
    @BindView(R.id.img_head)
    ImageView img_head;
    @BindView(R.id.checkbox)
    CheckBox check;
    @BindView(R.id.tv_detail_one_title)
    TextView tvDetailOneTitle;
    @BindView(R.id.tv_remain_time_title)
    TextView tvRemainTimeTitle;
    @BindView(R.id.tv_detail_two_title)
    TextView tvDetailTwoTitle;
    @BindView(R.id.pay_title)
    RelativeLayout payTitle;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.experience_container)
    LinearLayout experienceContainer;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.btn_yes)
    RadioButton btn_yes;
    @BindView(R.id.btn_no)
    RadioButton btn_no;
    @BindView(R.id.info1)
    LinearLayout info1;
    @BindView(R.id.info2)
    LinearLayout info2;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.fl_allergy)
    FrameLayout flAllergy;
    @BindView(R.id.tv_recipel)
    ShapeTextView tvRecipel;
    @BindView(R.id.tv_tag)
    ShapeTextView tvTag;
    @BindView(R.id.tv_state_words_num)
    TextView tvStateWordsNum;
    @BindView(R.id.tv_allergy_words_num)
    TextView tvAllergyWordsNum;
    @BindView(R.id.tv_past_words_num)
    TextView tvPastWordsNum;

    private MyFamilyListResponse myFamily;
    private DateTimeDialogFragment mDateTimeDialogFragment = null;
    private SchudeleDialogFragment mSchudeleDialogFragment = null;
    private PayDialog mPayDialog;

    MyAdapter adapter;
    Doctor doctor;
    Doctor.Schedule schedule;
    String scheduleId, orderId, resourceId, checkDetailId = "", fee;
    CloudResponse cloud;
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri;
    public ProgressDialog dialog;
    IWXAPI api;
    List<Photo> list = new ArrayList<>();
    int type;// 0  图文  1  云  2 云订单 3 药 4 聊天 5 图文订单
    private RulesDialogFragment mRulesDialogFragment;
    private CountDownTimer timer;
    private SelectPicModeDialog mSelectPicModeDialog = null;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    private int graphicType;

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 1;
            }
        });
        if (type == UIConstants.PayActivity_TYPE_0) {
            tvTitle.setVisibility(View.VISIBLE);
            payTitle.setVisibility(View.GONE);
            tvName.setText(doctor.docName);
            tvDepartment.setText(doctor.deptName);
            tvPrice.setText("¥" + doctor.fee);
            if (TextUtils.isEmpty(doctor.fee)) {
                getResourcePrice(doctor.id);
            } else {
                fee = Double.parseDouble(doctor.fee) * 100 + "";
            }
//            dateTime_container.setVisibility(View.GONE);
//            cloud_date_container.setVisibility(View.GONE);
            list.add(new Photo());
            adapter.notifyDataSetChanged();
            getDoctorDetail(doctor.id);
            info2.setVisibility(View.GONE);

        } else if (type == UIConstants.PayActivity_TYPE_1) {
            tvTitle.setVisibility(View.VISIBLE);
            payTitle.setVisibility(View.GONE);
            tvName.setText(doctor.docName);
            tvDepartment.setText(doctor.deptName);
            list.add(new Photo());
            adapter.notifyDataSetChanged();
            getDoctorDetail(doctor.id);
            info1.setVisibility(View.GONE);
        } else if (type == UIConstants.PayActivity_TYPE_2) {
            //待支付
            tvTitle.setVisibility(View.GONE);
            payTitle.setVisibility(View.VISIBLE);
            unableViews();
            startCountDownTimer(cloud.remainPayTime);
            getDetail(cloud.orderId);
            getRegistrationDetail(cloud.diagnoseId);
            info1.setVisibility(View.GONE);
        } else if (type == UIConstants.PayActivity_TYPE_3) {
            getDetail(orderId);
            getRegistrationDetail(cloud.diagnoseId);
        } else if (type == UIConstants.PayActivity_TYPE_5) {
            tvTitle.setVisibility(View.GONE);
            payTitle.setVisibility(View.VISIBLE);
            unableViews();
            startCountDownTimer(cloud.remainPayTime);
//            dateTime_container.setVisibility(View.GONE);
//            cloud_date_container.setVisibility(View.GONE);
            info2.setVisibility(View.GONE);
            getPicOrderDetail(cloud.orderId);
            getRegistrationDetail(cloud.diagnoseId);
        }

        btn_yes.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                flAllergy.setVisibility(View.VISIBLE);
            } else {
                flAllergy.setVisibility(View.GONE);
            }
        });
        mPermissionsChecker = new PermissionsChecker(mContext);

        edtState.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvStateWordsNum.setText(s.toString().length() + "/300");
            }
        });
        edtPast.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvPastWordsNum.setText(s.toString().length() + "/100");

            }
        });
        edtAllergy.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvAllergyWordsNum.setText(s.toString().length() + "/50");
            }
        });
    }

    @Override
    protected void initData() {
        graphicType = getIntent().getIntExtra(UIConstants.GRAPHIC_TYPE_FLAG, UIConstants.GRAPHIC_TYPE_1);
        if (graphicType == UIConstants.GRAPHIC_TYPE_1) {
            tvTitle.setText(R.string.graphic_type_consult);
        } else if (graphicType == UIConstants.GRAPHIC_TYPE_2) {
            tvTitle.setText(R.string.graphic_type_referral);
        }
        doctor = (Doctor) getIntent().getSerializableExtra(UIConstants.OBJ_Doctor);
        myFamily = (MyFamilyListResponse) getIntent().getSerializableExtra(UIConstants.OBJ_MyFamilyListResponse);
        if (myFamily != null) {
            tvPatientName.setText(myFamily.name);
            BaseApplication.currentFamilyId = myFamily.patientId;
        }

        cloud = (CloudResponse) getIntent().getSerializableExtra("cloudObj");
        type = getIntent().getIntExtra(UIConstants.PayActivity_TYPE_FLAG, 0);
        orderId = getIntent().getStringExtra("orderId");
        checkDetailId = getIntent().getStringExtra("checkDetailId");
        if (!UtilString.isEmpty(checkDetailId)) {
            queryCheckDetail();
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_pay;
    }


    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        if (TextUtils.isEmpty(tvPatientName.getText().toString())) {
            ToastUtil.showToast(mContext, "请先选择就诊人");
            return;
        }
        if (edtState.getText().toString().length() == 0 || edtAllergy.getText().toString().length() == 0 && btn_yes.isChecked()) {
            ToastUtil.showToast(mContext, "请填写主诉及过敏史");
            return;
        }
        if (!check.isChecked()) {
            ToastUtil.showToast(mContext, "请选择知情同意书及平台免责声明");
            return;
        }

        if (type != UIConstants.PayActivity_TYPE_5) {
            if (edtState.getText().toString().length() < 20) {
                showPayTipDialog();
                return;
            }
        }
        pay();
    }

    private void pay() {
        if (type == UIConstants.PayActivity_TYPE_0) {
            addOrder();
            BaseApplication.bookInfo = "您成功预约了" + doctor.docName + " " + doctor.deptName + " " + doctor.jobTitleName + "的图文咨询届时医生会与您图文+视频对话";
            BaseApplication.diagnoseType = 0;
        } else if (type == UIConstants.PayActivity_TYPE_1) {
            userSchedule();
//            BaseApplication.bookInfo = "您成功预约了" + tvScheduleTime.getText().toString() + " " + tvDateTime.getText().toString() + "的云门诊届时医生会与您图文+视频对话";
            BaseApplication.diagnoseType = 1;
            info1.setVisibility(View.GONE);
        } else if (type == UIConstants.PayActivity_TYPE_2) {
            createWXOrder(cloud.orderId);
        } else {
            createWXOrder(cloud.orderId);
        }
    }

    /**
     * “病情描述”的内容少于20个字
     * 支付前的提示弹框
     */
    private void showPayTipDialog() {
        PayTipDialog dialog = PayTipDialog.newInstance();
        dialog.setmListener(new PayTipDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                pay();
            }

            @Override
            public void onCancel() {
                edtState.requestFocus();
                nestedScrollView.scrollTo(0, edtState.getTop());
            }
        });
        dialog.show(getSupportFragmentManager(), "PayTipDialog");
    }

//    @OnClick(R.id.dateTime_container)
//    void dateTime_container() {
//        showDateTimeDialogFragment();
//    }

//    @OnClick(R.id.cloud_date_container)
//    void cloud_date_container() {
//        showScheduleDialogFragment();
//    }

    @OnClick(R.id.tv_agree)
    void agree() {
        showRulesDialogFragment();
    }


    /**
     * 查询预约的眼科信息
     *
     * @time 2021/1/8 19:46
     */

    private void queryCheckDetail() {
        RestProxy.getInstance().queryCheckDetail(checkDetailId, new Observer<BaseJsonResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseJsonResponse baseJsonResponse) {
                try {
                    String osUrl = baseJsonResponse.oS;
                    String oDUrl = baseJsonResponse.oD;
                    String url = baseJsonResponse.url;//说明视力或者屈光或者眼压有图片
                    String checkItemCode = baseJsonResponse.checkItemCode;

                    if (!UtilString.isEmpty(osUrl)) {
                        //说明是眼底，区分左右眼
                        Photo photo = new Photo();
                        photo.uri = osUrl;
                        photo.resourceId = baseJsonResponse.resourceId;
                        list.add(photo);
                        adapter.notifyDataSetChanged();
                    }
                    if (!UtilString.isEmpty(oDUrl)) {
                        //说明是眼底，区分左右眼
                        Photo photo = new Photo();
                        photo.uri = oDUrl;
                        photo.resourceId = baseJsonResponse.resourceId;
                        list.add(photo);
                        adapter.notifyDataSetChanged();
                    }
                    if (!UtilString.isEmpty(url)) {
                        Photo photo = new Photo();
                        photo.uri = url;
                        photo.resourceId = baseJsonResponse.resourceId;
                        list.add(photo);
                        adapter.notifyDataSetChanged();
                    }
                    List<BaseJsonResponse.Impression> impressionList = baseJsonResponse.impression;
                    StringBuilder miaoshu = new StringBuilder();
                    String miaoshuTitle = "";

                    if (!UtilList.isEmpty(impressionList)) {
                        BaseJsonResponse.Impression impressionBean = impressionList.get((impressionList.size() - 1));
                        //101 眼底照相检查 102 眼压检查 103 眼前节照相检查 104 视力检查 105 屈光检查
                        if ("102".equals(checkItemCode)) {
                            if (!UtilString.isEmpty(impressionBean.title)) {
                                miaoshuTitle = impressionBean.title + "--";
                            } else {
                                miaoshuTitle = "眼压测量结果（平均数值)--";
                            }
                            miaoshu.append(miaoshuTitle);
                            if (!UtilString.isEmpty(impressionBean.osEyePressure)) {
                                //左眼眼压
                                String eyeYaLeft = "左眼眼压: " + impressionBean.osEyePressure + ",";
                                miaoshu.append(eyeYaLeft);
                            }
                            if (!UtilString.isEmpty(impressionBean.odEyePressure)) {
                                String eyeYaRight = "右眼眼压: " + impressionBean.odEyePressure;
                                miaoshu.append(eyeYaRight);
                            }
                            edtState.setText(miaoshu.toString());
                        } else if ("104".equals(checkItemCode)) {
                            for (BaseJsonResponse.Impression impression : impressionList) {
                                miaoshu.append(impression.title).append(impression.eyeVision).append(",");
                            }
                            edtState.setText(miaoshu.toString());
                        } else if ("105".equals(checkItemCode)) {
                            for (BaseJsonResponse.Impression impression : impressionList) {
                                miaoshu.append(impression.title).append("--").append("球镜度数:").append(impression.ballDegree).append("柱镜度数:").append(impression.columnDegree).append("轴位:").append(impression.axis).append(",");
                            }
                            edtState.setText(miaoshu.toString());
                        }
                        Log.e("眼压集合---", baseJsonResponse.impression.size() + "");
                    }

                } catch (Exception e) {// 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @OnClick(R.id.patient_name_container)
    void patient_name_container() {
        if (getIntent().getBooleanExtra(UIConstants.CANNOT_SELECT_PATIENT, false)) {
            ToastUtil.showToast(this, getString(R.string.string_cannot_reselect_patient));
        } else {
            startActivityForResult(MyFamilyActivity.class, 1);

        }
    }

//    @OnClick(R.id.tv_doctor_detail)
//    public void onViewClicked() {
//        //查看医生详情
//        Bundle bundle = new Bundle();
//        bundle.putString("id", doctor.id);
//        bundle.putInt(UIConstants.DOCTORDETAILACTIVITY_TYPE_FLAG, UIConstants.DOCTORDETAILACTIVITY_TYPE_1);
//        startActivity(DoctorDetailActivity.class, bundle);
//    }

    /**
     * 上传图片
     *
     * @time 2020/12/2 9:43
     */

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        public MyAdapter() {
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_photo, parent, false));
        }

        @Override
        public void onBindViewHolder(@NotNull final Holder holder, final int position) {

            if (position == 0) {
                if (type == UIConstants.PayActivity_TYPE_1 || type == UIConstants.PayActivity_TYPE_0) {
                    holder.image.setImageResource(R.mipmap.btn_add_photo);
                    holder.btn_del_photo.setVisibility(View.GONE);
                } else {
                    if (!TextUtils.isEmpty(list.get(position).url)) {
                        ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).url, holder.image);
                    } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                        ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).uri, holder.image);
                    }
                }
            } else {
                if (!TextUtils.isEmpty(list.get(position).url)) {
                    ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).url, holder.image);
                } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                    ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).uri, holder.image);
                }
                holder.btn_del_photo.setVisibility(View.VISIBLE);
                holder.btn_del_photo.setOnClickListener(v -> {
                    list.remove(position);
                    notifyDataSetChanged();
                });

            }
            holder.image.setOnClickListener(v -> {
                if (type == UIConstants.PayActivity_TYPE_1 || type == UIConstants.PayActivity_TYPE_0) {
                    if (position == 0) {
                        if (list.size() > 20) {
                            ToastUtil.showToast(mContext, "上传图片数量已达20张");
                            return;
                        }
                        // 缺少权限时, 进入权限配置页面
                        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                            getPermission();
                        } else {
                            showSelectHeadPicDialog();
                        }
                    } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", list.get(position).uri);
                        bundle.putInt("type", 1);
                        PayActivity.this.startActivity(BigImageActivity.class, bundle);
                    } else if (!TextUtils.isEmpty(list.get(position).url)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", list.get(position).url);
                        bundle.putInt("type", 2);
                        PayActivity.this.startActivity(BigImageActivity.class, bundle);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
//            if (type == 1 || type == 0) {
//                return list.size() + 1;
//            }
            return list.size();
        }


        class Holder extends RecyclerView.ViewHolder {

            ImageView image;
            ImageView btn_del_photo;

            public Holder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.image);
                btn_del_photo = itemView.findViewById(R.id.btn_del_photo);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                showLoadingDialog(mContext);
                UploadImageUtil.uploadPic("1", "15", imgPathOri, "0", new UploadImageUtil.UploadCallBack() {
                    @Override
                    public void success(PicUploadResponse data) {
                        uploadImageSuccess(data);
                    }

                    @Override
                    public void fail() {
                        dismissLoadingDialog();
                    }
                });
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
//                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                    imgPathOri = UriUtils.formatUri(this, imgUriSel);
                    showLoadingDialog(mContext);
                    UploadImageUtil.uploadPic("1", "15", imgPathOri, "0", new UploadImageUtil.UploadCallBack() {
                        @Override
                        public void success(PicUploadResponse data) {
                            uploadImageSuccess(data);
                        }

                        @Override
                        public void fail() {
                            dismissLoadingDialog();
                        }
                    });
                }
                break;
            case 1:
                myFamily = (MyFamilyListResponse) data.getSerializableExtra(UIConstants.OBJ_MyFamilyListResponse);
                tvPatientName.setText(myFamily.name);
                BaseApplication.currentFamilyId = myFamily.patientId;
                break;
            default:
                break;
        }
    }

    private void uploadImageSuccess(PicUploadResponse data) {
        try {
            runOnUiThread(() -> {
                Photo photo = new Photo();
                photo.uri = imgPathOri;
                photo.resourceId = data.resourceId;
                list.add(photo);
                adapter.notifyDataSetChanged();
                dismissLoadingDialog();
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showDateTimeDialogFragment() {
        if (schedule == null) {
            ToastUtil.showToast(mContext, "请先选择日期");
            return;
        }
//        if (mDateTimeDialogFragment == null) {
        mDateTimeDialogFragment = DateTimeDialogFragment.newInstance(doctor.id, schedule.deptId, schedule.scheduledata, schedule.timeInterval);
        mDateTimeDialogFragment.setmListener((feedback, id) -> {
//            tvDateTime.setText(feedback);
            scheduleId = id;
            getResourcePrice(id);
            mSchudeleDialogFragment.dismiss();
        });
        mDateTimeDialogFragment.show(getSupportFragmentManager(), "DateTimeDialogFragment");
//        }
    }

    private void createCloudOrder() {
        StringBuilder listId = new StringBuilder();
        for (int i = 1; i < list.size(); i++) {
            listId.append(list.get(i).resourceId).append(",");
        }
        RestProxy.getInstance().createCloudOrder(BaseApplication.currentUserId, scheduleId, myFamily.patientId, edtState.getText().toString(), edtAllergy.getText().toString(), edtPast.getText().toString(), listId.toString(), new BaseObserver<OrderResponse>() {
            @Override
            public void onSuccess(OrderResponse orderResponse) {
//                showPayDialog(orderResponse.data.orderId);
                createWXOrder(orderResponse.orderId);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

        });
    }

    private void createWXOrder(String orderId) {
        showLoadingDialog(mContext);
        BaseApplication.currentOrderId = orderId;
        RestProxy.getInstance().createOrder(orderId, fee, "", "", new Observer<PayResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(PayResponse payResponse) {
                dismissLoadingDialog();
                switch (payResponse.getType) {
                    case 1:
                        showPayDialog(payResponse);
                        break;
                    case 2:
                        ToastUtil.showToast(mContext, "请到药店自取");
                        finish();
                        break;
                    case 3:
                        ToastUtil.showToast(mContext, "请到医院自取");
                        finish();
                        break;
                    case 4:
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", 1);
                        startActivity(WXPayEntryActivity.class, bundle);
                        ToastUtil.showToast(mContext, "医保已全额报销");
                        finish();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                dismissLoadingDialog();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void userSchedule() {
        RestProxy.getInstance().userSchedule(scheduleId, myFamily.patientId, doctor.id, doctor.deptId, "1", new Observer<StringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StringResponse stringResponse) {
                createCloudOrder();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getDetail(String orderId) {
        RestProxy.getInstance().getCloudOrderDetail(orderId, new BaseObserver<CloudResponse>() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(CloudResponse cloudOrderDetailResponse) {
                cloud = cloudOrderDetailResponse;
                tvName.setText(cloud.doctorName);
                tvDepartment.setText(cloud.deptName);
                tvPrice.setText("¥" + cloud.orderAmount);
                tvPatientName.setText(cloud.patientName);
//                tvScheduleTime.setText(cloud.scheduleDate);
//                tvDateTime.setText(cloud.scheduleTime);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
            }
        });
    }


    private void getPicOrderDetail(String orderId) {
        RestProxy.getInstance().getPicOrderDetail(orderId, new BaseObserver<CloudResponse>() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(CloudResponse cloudOrderDetailResponse) {
                cloud = cloudOrderDetailResponse;
                tvName.setText(cloud.doctorName);
                tvDepartment.setText(cloud.deptName);
                tvPrice.setText("¥" + cloud.orderAmount);
                tvPatientName.setText(cloud.patientName);
                fee = cloud.orderAmount;
//                tvScheduleTime.setText(cloud.scheduleDate);
//                tvDateTime.setText(cloud.scheduleTime);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
            }
        });
    }


    private void addOrder() {
        RestProxy.getInstance().addOrder(graphicType, doctor.id, BaseApplication.currentFamilyId, doctor.fee, new BaseObserver<OrderResponse>() {
            @Override
            public void onSuccess(OrderResponse orderResponse) {
                savePatientState(orderResponse.diagnoseId);
//                showPayDialog(orderResponse.data.orderId);
                createWXOrder(orderResponse.orderId);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }

    private void savePatientState(String diagnoseId) {
        StringBuilder listId = new StringBuilder();
        for (int i = 1; i < list.size(); i++) {
            listId.append(list.get(i).resourceId).append(",");
        }
        RestProxy.getInstance().savePatientState(BaseApplication.currentFamilyId, doctor.id, edtState.getText().toString(), edtAllergy.getText().toString(), edtPast.getText().toString(), listId.toString(), diagnoseId, new BaseObserver<String>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onSuccess(String result) {

            }
        });
    }


    private void getRegistrationDetail(String diagnoseId) {
        RestProxy.getInstance().getRegistrationDetail(diagnoseId, new BaseObserver<RegistrationDetailResponse>() {

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onSuccess(RegistrationDetailResponse registrationDetailResponse) {
                edtState.setText(registrationDetailResponse.oneselfState);
                edtPast.setText(registrationDetailResponse.pastHistory);
                if (TextUtils.isEmpty(registrationDetailResponse.allergyHistory)) {
                    btn_no.setChecked(true);
                } else {
                    btn_yes.setChecked(true);
                    edtAllergy.setText(registrationDetailResponse.allergyHistory);
                }
                if (!UtilList.isEmpty(registrationDetailResponse.resultList)) {
//                    rlPayPhoto.setVisibility(View.VISIBLE);
                    list.clear();
                    list.addAll(registrationDetailResponse.resultList);
                    adapter.notifyDataSetChanged();
                } else {
//                    rlPayPhoto.setVisibility(View.GONE);
                }
                getDoctorDetail(registrationDetailResponse.doctorId);
            }
        });
    }


    private void getDoctorDetail(String id) {
        RestProxy.getInstance().getDoctorDetail(id, new BaseObserver<Doctor>() {
            @Override
            public void onSuccess(Doctor doctorDetailResponse) {
                doctor = doctorDetailResponse;
                tvName.setText(doctorDetailResponse.docName);
                tvDepartment.setText(doctorDetailResponse.deptName);
                tv_hospital.setText(doctorDetailResponse.hospitalName);
                if (doctorDetailResponse.isPrescription == 0) {
                    tvTag.setVisibility(View.GONE);
                } else {
                    tvTag.setVisibility(View.VISIBLE);
                }
                tv_star.setText(doctorDetailResponse.score);
                ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, doctorDetailResponse.thumbnailUrl, img_head);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }


    private void getResourcePrice(String doctorId) {
        RestProxy.getInstance().getResourcePrice(doctorId, new BaseObserver<StringResponse>() {
            @Override
            public void onSuccess(StringResponse stringResponse) {
                fee = Double.parseDouble(stringResponse.price) * 100 + "";
                tvPrice.setText("¥" + doctor.fee);
            }
        });
    }

    private void unableViews() {
//        dateTime_container.setEnabled(false);
//        cloud_date_container.setEnabled(false);
        patient_name_container.setEnabled(false);
        edtAllergy.setEnabled(false);
        edtPast.setEnabled(false);
        edtState.setEnabled(false);
        btn_no.setEnabled(false);
        btn_yes.setEnabled(false);
        check.setChecked(true);
    }

    private void startCountDownTimer(String remainPayTime) {
        Log.e("倒计时===", remainPayTime);
        final int parseInt = Integer.parseInt(remainPayTime);
        timer = new CountDownTimer(parseInt * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                tvRemainTimeTitle.setText(millisUntilFinished / 60000 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
            }

            @Override
            public void onFinish() {
                //倒计时为0时执行此方法
                tvRemainTimeTitle.setText("已超时");
                timer.cancel();
                tvDetailOneTitle.setVisibility(View.GONE);
                tvDetailTwoTitle.setVisibility(View.GONE);
            }
        };
        timer.start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        if (mDateTimeDialogFragment != null && mDateTimeDialogFragment.isShowing()) {
            mDateTimeDialogFragment.dismiss();
            mDateTimeDialogFragment = null;
        }
        if (mPayDialog != null && mPayDialog.isShowing()) {
            mPayDialog.dismiss();
            mPayDialog = null;
        }
        if (mRulesDialogFragment != null && mRulesDialogFragment.isShowing()) {
            mRulesDialogFragment.dismiss();
            mRulesDialogFragment = null;
        }
        if (mSchudeleDialogFragment != null && mSchudeleDialogFragment.isShowing()) {
            mSchudeleDialogFragment.dismiss();
            mSchudeleDialogFragment = null;
        }
        if (mSelectPicModeDialog != null && mSelectPicModeDialog.isShowing()) {
            mSelectPicModeDialog.dismiss();
            mSelectPicModeDialog = null;
        }


    }

    /**
     * 拍照还是手机相册弹窗
     *
     * @time 2020/12/2 9:53
     */
    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        imgUriOri = FileProvider.getUriForFile(mContext, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }


    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    protected File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);//申请退药
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(PayActivity.this);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }


    private void showRulesDialogFragment() {
        mRulesDialogFragment = RulesDialogFragment.newInstance("1");
        mRulesDialogFragment.setmListener(() -> mRulesDialogFragment.dismiss());
        mRulesDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
    }


    private void showPayDialog(final PayResponse payResponse) {
        if (TextUtils.isEmpty(payResponse.ownAmount)) {
            mPayDialog = PayDialog.newInstance(tvPrice.getText().toString());
        } else {
            mPayDialog = PayDialog.newInstance(payResponse.ownAmount);
        }
        mPayDialog.show(getSupportFragmentManager(), "mPayDialog");
        mPayDialog.setmListener(new PayDialog.OnItemClickListener() {
            @Override
            public void callback() {
                BaseApplication.currentWXId = payResponse.appid;
                api = WXAPIFactory.createWXAPI(mContext, payResponse.appid);
                // 将该app注册到微信
                api.registerApp(payResponse.appid);
                PayReq request = new PayReq();
                request.appId = payResponse.appid;
                request.partnerId = payResponse.partnerid;
                request.prepayId = payResponse.prepayid;
                request.packageValue = "Sign=WXPay";
                request.nonceStr = payResponse.noncestr;
                request.timeStamp = payResponse.timestamp;
                request.sign = payResponse.sign;
                api.sendReq(request);
                EventBus.getDefault().post(new RefreshEvent());
                finish();
            }

            @Override
            public void onCancel() {
//                startActivity(MainActivity.class);
//                EventBus.getDefault().postSticky(new Logout(2));
                Bundle bundle = new Bundle();
                bundle.putInt("page", 1);
                startActivity(MyAskActivity.class, bundle);
                mPayDialog.dismiss();
                finish();
            }
        });
    }


    private void showScheduleDialogFragment() {
//        if (mDateTimeDialogFragment == null) {
        mSchudeleDialogFragment = SchudeleDialogFragment.newInstance(doctor.id);
        mSchudeleDialogFragment.setmListener(schedule -> {
            PayActivity.this.schedule = schedule;
            tvPrice.setText("");
//            tvScheduleTime.setText(schedule.scheduleTime);
//            tvDateTime.setText("");
            scheduleId = "";
            mSchudeleDialogFragment.dismiss();
        });
        mSchudeleDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
//        }
    }
}
